<template>
  <div class="form">
    <el-button @click="$router.push('/student')" circle>
      <el-icon>
        <ArrowLeft />
      </el-icon>
    </el-button>

    <el-form ref="studentFormRef" style="width:70%;height:100%" :model="updateStudent" :rules="rules" label-width="100px"
      label-positon="right">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="updateStudent.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="updateStudent.gender" placeholder="点击选择" class="filter-item">
          <el-option v-for="options in genderOptions" :key="options._id" :label="options.name" :value="options._id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所在学校" prop="school">
        <el-autocomplete v-model="updateStudent.school" :fetch-suggestions="querySearchSchool" placeholder="请输入学校名称"></el-autocomplete>
      </el-form-item>

      <el-form-item label="专业" prop="major">
        <el-autocomplete v-model="updateStudent.major" :fetch-suggestions="querySearchMajor" placeholder="请输入专业名称"></el-autocomplete>
      </el-form-item>

      <el-form-item label="年级" prop="grade">
        <el-select v-model="updateStudent.grade" placeholder="点击选择" class="filter-item">
          <el-option v-for="options in gradeOptions" :key="options._id" :label="options.name" :value="options._id" />
        </el-select>
      </el-form-item>

      <el-form-item label="学历" prop="education">
        <el-select v-model="updateStudent.education" placeholder="点击选择" class="filter-item">
          <el-option v-for="options in educationOptions" :key="options._id" :label="options.name"
            :value="options._id" />
        </el-select>
      </el-form-item>

      <el-form-item label="学习方向" prop="direction">
        <el-select v-model="updateStudent.direction" placeholder="点击选择" class="filter-item">
          <el-option v-for="options in directionOptions" :key="options._id" :label="options.name"
            :value="options._id" />
        </el-select>
      </el-form-item>

      <el-form-item label="身份证号码" prop="id_number">
        <el-input v-model="updateStudent.id_number" placeholder="请输入身份证号码"/>
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="updateStudent.phone" placeholder="请输入联系电话"/>
      </el-form-item>

      <el-form-item label="家长姓名" prop="parent">
        <el-input v-model="updateStudent.parent" placeholder="请输入家长姓名"/>
      </el-form-item>

      <el-form-item label="家长联系电话" prop="parent_phone">
        <el-input v-model="updateStudent.parent_phone" placeholder="请输入家长联系电话"/>
      </el-form-item>

      <el-form-item label="家庭住址" prop="address">
        <el-input v-model="updateStudent.address" placeholder="请输入家庭住址"/>
      </el-form-item>

      <el-form-item label="QQ号码" prop="qq">
        <el-input v-model="updateStudent.qq" placeholder="请输入QQ号码"/>
      </el-form-item>

      <el-form-item label="所在班级" prop="class">
        <el-select v-model="updateStudent.class" placeholder="点击选择" class="filter-item">
          <el-option v-for="options in classOptions" :key="options._id" :label="options.classname"
            :value="options._id" />
        </el-select>
      </el-form-item>

      <el-form-item label="入学时间" prop="admission_date">
        <el-date-picker v-model="updateStudent.admission_date" type="date" aria-placeholder="点击选择" class="filter-item"
          value-format="YYYY-MM-DD" ></el-date-picker>
      </el-form-item>

      <el-form-item label="授课教师" prop="teacher_id">
        <el-select v-model="updateStudent.teacher_id" placeholder="点击选择" class="filter-item">
          <el-option v-for="options in teacherOptions" :key="options._id" :label="options.name" :value="options._id" />
        </el-select>
      </el-form-item>

      <el-form-item label="学管" prop="manager_id">
        <el-select v-model="updateStudent.manager_id" placeholder="点击选择" class="filter-item">
          <el-option v-for="options in managerOptions" :key="options._id" :label="options.name" :value="options._id" />
        </el-select>
      </el-form-item>

      <el-form-item label="照片" prop="prctures">
        <!-- accept用于过滤图片，只显示图片 -->
        <el-upload :action="baseAPI + '/manage/img/upload'" list-type="picture-card" :auto-upload="true" name="image"
          accept="image/*" :file-list="fileList" :on-change="handleChange" :before-upload="beforeAvatarUpload">
          <el-icon>
            <Plus />
          </el-icon>

          <template #file="{ file }">
            <div>
              <img :src="file.url" alt="" class="el-upload-list__item-thumbnail" />
              <span class="el-upload-list__item-actions">
                <span @click="handlePictureCardPreview(file)"><el-icon><zoom-in /></el-icon></span>
                
                <span v-if="!disabled" @click="handleDownload(file)"><el-icon>
                    <Download />
                  </el-icon></span>
                
                  <span v-if="!disabled" @click="handleRemove(file)"><el-icon>
                    <Delete />
                  </el-icon></span>
              </span>
            </div>
          </template>
        </el-upload>

        <!-- 放大显示图片 -->
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="备注" prop="note">
        <Editor v-model="updateStudent.note" :api-key="tiny.apiKey"></Editor>
      </el-form-item>


    </el-form>

  </div>
  <div slot="footer" class="dialog-footer">
    <el-button size="large" type="primary"
      @click="updateStudent._id == undefined ? addData(studentFormRef) : updateData(studentFormRef)">确定</el-button>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, resolveComponent } from 'vue'

import { ElMessage, type FormInstance, type FormRules, type UploadFile, type UploadProps, type UploadUserFile } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import type { studentInfoData } from '@/api/student/type'

import useStuStore from '@/store/modules/student';
import useClassStore from '@/store/modules/class';
import useRoleStore from '@/store/modules/role';
import useUserStore from '@/store/modules/user';
import type { roleInfoData } from '@/api/role/type';
import type { userInfoData } from '@/api/user/type';
import type { cla } from '@/api/class/type';
import useSchoolStore from '@/store/modules/school';
import majorStore from '@/store/modules/major';
import type { schoolInfoData } from '@/api/school/type';
import type { majorInfoData } from '@/api/major/type';
import Editor from "@tinymce/tinymce-vue"
const stuStore = useStuStore();
const classStore = useClassStore();
const roleStore = useRoleStore();
const userStore = useUserStore();
const schoolStore = useSchoolStore();
const majorSto = majorStore()

let roleOptions = ref<roleInfoData[]>([]);
let userOptions = ref<userInfoData[]>([]);
let classOptions = ref<cla[] | undefined>([])
let schoolOptions = ref<schoolInfoData[]>([])
let majorOptions = ref<majorInfoData[]>([])
const $router = useRouter()
const $route = useRoute()

const studentFormRef = ref<FormInstance>()
const updateStudent = ref<studentInfoData>({
  _id: undefined,
  name: "",
  gender: "",
  school: "",
  major: "",
  grade: "",
  education: "",
  direction: "",
  id_number: "",
  phone: "",
  parent: "",
  parent_phone: "",
  address: "",
  qq: "",
  class: "",
  admission_date: "",
  teacher_id: "",
  manager_id: "",
  pictures: [],
  note: "",
})

//角色为教师的id
let teacher_role_id = ref<string>("")
//角色为学管的id
let manager_role_id = ref<string>("")
//教师列表
let teacherOptions = ref<userInfoData[]>([])
//学管列表
let managerOptions = ref<userInfoData[]>([])
//性别/年级/学历/学习方向数据类型
interface FilterData {
  _id: string
  name: string
}
//性别数据列表
let genderOptions = ref<FilterData[]>([
  { _id: "1", name: "男" },
  { _id: "0", name: "女" },
])
//年级数据列表
let gradeOptions = ref<FilterData[]>([
  { _id: "1", name: "大一" },
  { _id: "2", name: "大二" },
  { _id: "3", name: "大三" },
  { _id: "4", name: "大四" },
  { _id: "5", name: "在读研究生" }
])
//学历数据列表
let educationOptions = ref<FilterData[]>([
  { _id: "1", name: "专科" },
  { _id: "2", name: "本科" },
  { _id: "3", name: "硕士" },
  { _id: "4", name: "社会" },
])
//学习方向数据列表
let directionOptions = ref<FilterData[]>([
  { _id: "1", name: "web前端" },
  { _id: "2", name: "Java" },
  { _id: "3", name: "C/C++" },
  { _id: "4", name: "少儿编程" },
  { _id: "5", name: "产品经理" },
])
//过渡要显示的数据
const dataFilter = (_id: string, options: any) => {
  //@ts-ignore
  const obj = options?.find(item => item._id == _id);
  return obj ? obj.name : ""
}
//过滤班级 
const classFilter = (_id: string, options: any) => {
  //@ts-ignore
  const obj = options?.find(item => item._id == _id);
  return obj ? obj.classname : ""
}
const getRoleList = () => {
  roleStore.roleList().then(() => {
    roleOptions.value = roleStore.roles as roleInfoData[]
    roleOptions.value?.forEach(item => {
      if (item.name == "教师") {
        teacher_role_id.value = item._id as string
      } else if (item.name == "学管") {
        manager_role_id.value = item._id as string
      }
    })
  })
}
//获取用户列表
const getUserList = () => {
  userStore.getUserAll().then(() => {
    userOptions.value = userStore.users as userInfoData[]
    userOptions.value.forEach(item => {
      if (item.role_id == teacher_role_id.value) {
        teacherOptions.value.push(item)
      } else if (item.role_id == manager_role_id.value) {
        managerOptions.value.push(item)
      }
    })
  })
}
//获取班级列表
const getClassList = () => {
  classStore.allClass().then(() => {
    classOptions.value = classStore.classes
  })
  //
}
//获取学校列表
const getSchoolList = () => {
  schoolStore.allSchool().then(res => {
    schoolOptions.value = res as schoolInfoData[];

  })
}
//获取专业列表
const getMajorList = () => {
  majorSto.allMajor().then(res => {
    majorOptions.value = res as majorInfoData[]
  })
}
//提示所有学校
const querySearchSchool = (queryString: string, callback: Function) => {
  // 1. 过滤出包含用户输入的学校（不区分大小写）
  const filteredSchools = schoolOptions.value.filter(school =>
    school.schoolname.includes(queryString)
  );

  // 2. 格式化为 autocomplete 要求的格式：[{ value: '学校名称' }, ...]
  const suggestions = filteredSchools.map(school => ({ value: school.schoolname }));

  // 3. 将建议列表传给组件（必须调用 callback，组件才能显示建议）
  callback(suggestions);
};


//提示所有专业
const querySearchMajor = (queryString: string, callback: Function) => {
  // 1. 过滤出包含用户输入的学校（不区分大小写）
  const filteredMajors = majorOptions.value.filter(major =>
    major.majorname.includes(queryString)
  );

  // 2. 格式化为 autocomplete 要求的格式：[{ value: '学校名称' }, ...]
  const suggestions = filteredMajors.map(major => ({ value: major.majorname }));

  // 3. 将建议列表传给组件（必须调用 callback，组件才能显示建议）
  callback(suggestions);
};

//检测
const validatePhone = (rule: any, value: any, callback: any) => {
    value = value.trim();
    const phoneReg = /^1[3-9]\d{9}$/;
    if (value == "") {
        callback(new Error("请输入手机号码"))
    } else if (!phoneReg.test(value)) {
        callback(new Error("请输入正确的手机号码"))
    } else {
        callback();
    }
}
const validateIdNumber = (rule: any, value: any, callback: any) => {
    value = value.trim();
    const reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  if (value == "") {
    return callback(new Error('请输入身份证号码'))
  }else if(!reg.test(value)){
    return callback(new Error('请输入正确的身份证号码'));
  }else {
    return callback()
  }
};
const rules = reactive<FormRules>({
  name: [{ required:true,message:"请输入姓名", trigger: 'blur' }],
  gender:[{ required:true,message:"请选择性别", trigger: 'blur'}],
  direction:[{required:true,message:"请选择学习方向",trigger: 'blur'}],
  id_number:[{validator:validateIdNumber,trigger: 'blur'}],
  phone:[{validator:validatePhone,trigger: 'blur'}],
  class:[{required:true,message:"请选择班级",trigger: 'blur'}],
  admission_date:[{required:true,message:"请选择入学时间",trigger: 'blur'}],
  teacher_id:[{required:true,message:"请选择授课教师",trigger: 'blur'}],
  manager_id:[{required:true,message:"请选择学管",trigger: 'blur'}],
});

/* 添加按钮触发的操作 */
const addData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
         updateStudent.value.pictures = getImgs();
        stuStore.addStu(updateStudent.value).then(()=>{
          $router.replace("/student")
        })
    } else {
      console.log('error submit!')
    }
  })
}

/* 更新按钮出发的操作 */
const updateData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
        updateStudent.value.pictures = getImgs();
        stuStore.updateStu(updateStudent.value).then(res=>{
          $router.replace("/student")
        })
    } else {
      return
    }
  })
}


const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

/* 图片上传所需方法 */
//在ts/vue文件中想使用env的环境变量，需要在tsconfig.json文件下添加属性types:["vite/client"],
const baseURL = import.meta.env.VITE_APP_SERVICE_URL
const baseAPI = import.meta.env.VITE_APP_BASE_API
import request from '@/utils/request';

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const fileList = ref<UploadUserFile[]>([])
//文件状态改变时的钩子，添加文件上传成功和上传失败时候都会被调用
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  if (uploadFile.status == "success") {
    const result = uploadFile.response;
    //@ts-ignore
    if (result.status == 0) {
      //@ts-ignore
      const { name, url } = result.data;
      uploadFile = uploadFiles[uploadFiles.length - 1];
      uploadFile.name = name;
      uploadFile.url = url;

    }
  }
  fileList.value = uploadFiles
}

//获取所有已上传图片名称数组
const getImgs = () => {
  return fileList.value.map(item => item.name)
}

const handleRemove = (file: UploadFile) => {
  request.post<any, any>('/manage/img/delete', { name: file.name }).then(res => {
    if (res.status == 0) {
      fileList.value.splice(fileList.value.indexOf(file), 1)
    }
  })
}
//点击放大镜放大图片
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
const handleDownload = (file: UploadFile) => {

}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
/* 富文本编辑框 */
// const tiny = reactive({
//     apiKey:"g2yfm8dsvvcqidwwh6hyj0xjkwmqjgy5mtp8ldw0gm191tsj",
//     init:{
//       toolbar_mode:"sliding",
//       toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | outdent indent',
//       plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table help wordcount',
//       tinycomment_mode:"embedded",
//       tinycomments_author: 'Author name',
//       mergetags_list:[
//         { value:"First.Name", title:"First Name" },
//         { value:"Email", title:"Email" },
//       ],
//       ai_request: (_request:any,repondWith:any)=>repondWith.string(()=>Promise.reject("See docs to implement AI Assistant")),
//     },
// })
const tiny = reactive({
    apiKey: "w8593t1vo6t8c9rf9zdr5m40p28g9j790kfdk0lema1vq658",
    init: {
        toolbar_mode: 'sliding',
        plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pageembed linkchecker a11ychecker tinymcespellchecker permanentpen powerpaste advtable advcode editimage advtemplate ai mentions tinycomments tableofcontents footnotes mergetags autocorrect typography inlinecss',
        toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | addcomment showcomments | spellcheckdialog a11ycheck typography | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat',
        tinycomments_mode: 'embedded',
        tinycomments_author: 'Author name',
        mergetags_list: [
          { value: 'First.Name', title: 'First Name' },
          { value: 'Email', title: 'Email' },
        ],
        ai_request: (_request:any, respondWith:any) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")),
    },
})

/* 编辑的操作 */
//编辑页面的页面填充
const getStu = ()=>{
  const {_id} = $route.params;
  if(_id != "-1"){
      stuStore.FindById(_id as string).then(res=>{
      updateStudent.value =  {...res}
      const { pictures } = res as studentInfoData;
      if(pictures && pictures.length != 0){
         fileList.value = pictures.map(item => ({name:item,url:baseAPI + "/upload/" + item}))
      }
    })
  }
    
}
onMounted(() => {
  getRoleList();
  getUserList();
  getClassList();
  getSchoolList();
  getMajorList();
  //编辑操作的页面填充
  getStu();
})
</script>
<style scoped>
.form {
  margin-top: 50px;

  display: flex;
  justify-content: center;
}

.dialog-footer {
  position: absolute;
  right: 14%;
}
/* #tiny-vue_39015419621757574129244{
  border: 1px solid black;
} */
</style>